class ArticlesController < ApplicationController
  before_filter :login_required, :except => [ :show, :index ]
  before_filter :find_user, :find_discipline, :except => [ :index ]

  def index
    @articles = Article.paginate :page => params[:page], :order => 'updated_at DESC'
  end

  def show
    @article = Article.find(params[:id])
  end

  def new
    @article = Article.new
  end

  def edit
    @article = Article.find_by_id_and_user_id(params[:id], current_user.id)
  end

  def create
    @article = Article.new(params[:article])
    @document = Document.new(:uploaded_data => params[:uploaded_data]) 
    @article.document = @document
    @article.user = current_user
    @article.discipline = @discipline
    respond_to do |format|
      if @document.valid? and @article.save
        deliver_article_notification(@article)
        flash[:notice] = "#{Article} was successfully created."
        format.html { redirect_to discipline_article_path(@discipline, @article) }
      else
        format.html { render :action => "new" }
      end
    end
  end

  def update
    @article = Article.find_by_id_and_user_id(params[:id], current_user.id)
    @document = Document.new(:uploaded_data => params[:uploaded_data]) 
    @article.document_versions << @document
    respond_to do |format|
      if @document.valid? and @article.update_attributes(params[:article])
        flash[:notice] = "#{Article} was successfully updated."
        format.html { redirect_to discipline_article_path(@discipline, @article) }
      else
        format.html { render :action => "edit" }
      end
    end
  end

  def destroy
    @article = Article.find(params[:id])
    @article.destroy
    flash[:notice] = "#{Article} was sucessfully deleted."

    respond_to do |format|
      format.html { redirect_to discipline_url(@discipline) }
    end
  end

  protected

  def deliver_article_notification(article)
    article.discipline.users.each do |user|
      UserMailer.deliver_new_article_notification(:to => user, :discipline => article.discipline, :article => article, :link => discipline_article_url(article.discipline, article)) if user != article.user and user.email_notifications?
    end
  end

  def authorized?
    logged_in? and current_user.admin? or (params[:id].nil? || Article.find(params[:id]).user == current_user) or %w(index new create show).include?(action_name)
  end

end
